/*
 * Copyright (C) 2010-2011 Comcast Cable.  All Rights Reserved.
 */
package com.hercules.android.receiver.painting;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.hercules.android.receiver.AndroidReceiver;
import com.hercules.android.receiver.DebugHelper;

/**
 * Simple POJO that contains image related data. Bitmap and view that uses it for display.
 * <p>
 * <b>Thread safety:</b> It uses synchronization on getter and setters, also collections of views and image resources
 * are thread safe.
 *
 * @author 7realm
 * @version 1.0
 */
public class ImageData {

    private boolean loadComplete = false;
    
    private byte[] bitmapData = null;
    
    private int usedTime = 0;
    
    private Bitmap cachedBitmap = null;
    
    private AndroidReceiver receiver = null;
    
    public final static int TEND_TO_CACHE_USED_TIME = 1;
    
    /**
     * Gets the bitmap, that will be loaded from url.
     *
     * @return the bitmap, that will be loaded from url
     */
    public synchronized Bitmap getBitmap() {
		++ usedTime;
		
		if (cachedBitmap != null) {
			return cachedBitmap;
		} else if (bitmapData != null) {
			if (usedTime > TEND_TO_CACHE_USED_TIME && 
				DebugHelper.usedImageMemorySize < DebugHelper.imageMemoryPoolSize) {
				cachedBitmap = BitmapFactory.decodeByteArray(bitmapData, 0, bitmapData.length);
				DebugHelper.usedImageMemorySize += bitmapData.length;
				bitmapData = null;
				return cachedBitmap;
			} else {
				Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapData, 0, bitmapData.length);
	    		return bitmap;
			}
		}
    	
        return null;
    }

    public synchronized void setBitmap(Bitmap bitmap) {
    	cachedBitmap = bitmap;
    }
    
	/**
	 * @param loadComplete the loadComplete to set
	 */
	public synchronized void setLoadComplete(boolean loadComplete) {
		this.loadComplete = loadComplete;
	}

	/**
	 * @return the loadComplete
	 */
	public synchronized boolean isLoadComplete() {
		return loadComplete;
	}

	/**
	 * @param bitmapData the bitmapData to set
	 */
	public synchronized void setBitmapData(byte[] bitmapData) {
		this.bitmapData = bitmapData;
	}

	/**
	 * @return the bitmapData
	 */
	public synchronized byte[] getBitmapData() {
		return bitmapData;
	}

	/**
	 * @param receiver the receiver to set
	 */
	public void setReceiver(AndroidReceiver receiver) {
		this.receiver = receiver;
	}

	/**
	 * @return the receiver
	 */
	public AndroidReceiver getReceiver() {
		return receiver;
	}
}
